/*
 * Copyright 2016-2036 the original author or authors.
 * 
 * COMMERCIAL USE OF THIS SOFTWARE WITHOUT WARRANTY IS NOT ALLOWED.
 * Use is subject to license terms! You can distribute a copy of this software
 * to others for free. This software is a non-profit and open-source project.
 * Any contribution to this project will make it better.
 * All rights reserved! Owned by Stephen Liu.
 * 
 */
package com.github.raffle.concurrent;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author ste7en.liu@gmail.com
 * @since 2016/12/4
 */
public class MscLock {

    private AtomicReference<Node> tail;

    //当前节点信息，每个线程自己维护
    private ThreadLocal<Node> myNode;

    public void lock() {
        Node node = myNode.get();
        Node prev = tail.getAndSet(node);

        if (prev != null) {
            node.locked = true;
            prev.next = node;
            while (node.locked) {
                //
            }
        }
    }

    private void unlock() {
        Node node = myNode.get();
        if (node.next == null) {
            if (tail.compareAndSet(node, null))
                return;
            while (node.next == null) {
                //
            }
        }
        node.next.locked = false;
        node.next = null;
    }

    class Node {
        boolean locked;
        Node next;
    }
}
